package sys.news.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 数据库的获取和关闭工具
 * @author bdqn-li
 *
 */
public class DBUtil {	
	//连接池
	public static DataSource ds = new ComboPooledDataSource();
	/**
	 * 获取连接对象
	 * @return
	 */
	public static Connection getConnection(){
		//2.获取连接
		Connection conn = null;
		try {
			conn = ds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 关闭连接
	 * @param conn
	 * @param stmt
	 * @param rs
	 */
	public static void closeAll(Connection conn,Statement stmt,ResultSet rs){
		try {
			if(rs != null)rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(stmt != null)stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(conn != null)conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 增删改的封装方法(无事务控制)
	 * @param sql
	 * @param params
	 * @return
	 */
	public static int update(String sql,Object[] params){
		int result = 0;
		Connection conn = null;
		PreparedStatement pstmt = null;
		try{
			//1.获取连接
			conn = DBUtil.getConnection();
			//3.预处理对象
			pstmt = conn.prepareStatement(sql);
			//4.传参
			if(params != null){
				for(int i=0;i<params.length;i++){
					pstmt.setObject(i+1, params[i]);
				}
			}
			//5.处理结果
			result = pstmt.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			//6.关闭连接
			DBUtil.closeAll(conn, pstmt, null);
		}
		return result;
	}
	
	/**
	 * 增删改的封装方法(事务控制)
	 * @param sql
	 * @param params
	 * @return
	 */
	public static int update(String sql,Object[] params,Connection conn){
		int result = 0;
		PreparedStatement pstmt = null;
		try{
			//3.预处理对象
			pstmt = conn.prepareStatement(sql);
			//4.传参
			if(params != null){
				for(int i=0;i<params.length;i++){
					pstmt.setObject(i+1, params[i]);
				}
			}
			//5.处理结果
			result = pstmt.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 关闭连接(事务控制)
	 * @param conn
	 */
	public static void closeConn(Connection conn){
		try {
			if(conn != null)conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
